package com.qianfeng.ls.web;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.qianfeng.ls.entity.AdminEntity;
import com.qianfeng.ls.entity.ResponseResult;
import com.qianfeng.ls.finalstr.FruitsFinal;
import com.qianfeng.ls.pojo.AdminPojo;
import com.qianfeng.ls.pojo.AuthPojo;
import com.qianfeng.ls.pojo.RolePojo;
import com.qianfeng.ls.service.IAdminService;
import com.qianfeng.ls.service.IRoleService;
import com.qianfeng.ls.util.StringUtil;
import org.apache.tools.ant.taskdefs.condition.Http;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

@Controller
public class AdminController {

    @Autowired
    IAdminService adminService;

    @Autowired
    IRoleService roleService;

    //跳转到登录页面
    @RequestMapping("/jump")
    public String jumpLogin() {

        return "adminlogin";
    }

    //登录
    @RequestMapping("/adminLogin")
    public ModelAndView adminLogin(AdminEntity ae, HttpServletRequest request) {
        ModelAndView mv = new ModelAndView();

        if (null == ae) {
            mv.setViewName("fail");
            mv.addObject("errorMsg", "系统异常,请稍后再试");
            return mv;
        }

        if (StringUtil.isEmpty(ae.getAacount())) {
            mv.setViewName("adminlogin");
            mv.addObject("errorMsg", "请输入用户名");
            return mv;
        }

        if (StringUtil.isEmpty(ae.getApass())) {
            mv.setViewName("adminlogin");
            mv.addObject("errorMsg", "请输入密码");
            return mv;
        }

        //对密码进行MD5加密
        ae.setApass(StringUtil.MD5Encode(ae.getApass()));

        //执行登陆
        AdminPojo adminPojo = adminService.adminLogin(ae);

        if (null == adminPojo) {
            mv.setViewName("adminlogin");
            mv.addObject("errorMsg", "用户名密码错误,登录失败");
        } else {

            //将信息保存到session里面;
            request.getSession().setAttribute("adminPojo", adminPojo);

            //获取当前用户的所有权限
            List<RolePojo> roles = adminPojo.getRoles();
            Set<AuthPojo> auths = new HashSet<AuthPojo>();
            for(RolePojo rp : roles){
                auths.addAll(rp.getAuths());
            }

            //获取用户的所有菜单
            Set<AuthPojo> menu = new HashSet<AuthPojo>();
            for(AuthPojo ap:auths){

                if(ap.getAutype() == 1){ //菜单栏
                    menu.add(ap);
                }
            }

            //遍历用户所有的权限
            StringBuilder strAuths = new StringBuilder(); //以字符串的方式存放用户所有的权限
            for(AuthPojo ap : auths){
                strAuths.append("/").append(ap.getAupath());
            }

            request.getSession().setAttribute("strAuths",strAuths.toString());//用户权限的字符串
//            request.getSession().setAttribute("auths",auths);//某某用户的所有权限
            request.getSession().setAttribute("menu",menu);//用户的所有菜单

            //区分1级菜单,1级菜单下面的2级菜单

            mv.setViewName("index");
        }

        return mv;
    }

    //管理员列表; 搜索 分页 都是调用的这个请求
    @RequestMapping("/adminlist")
    public String adminList(AdminEntity ae,HttpServletRequest request) {

        //设置当前页,和每页显示的记录数
        PageHelper.startPage(ae.getPageNum(),ae.getPageSize());

        //查询所有的管理员
        List<AdminPojo> list = adminService.queryAdmins(ae); //适用于数据量并不多的情况下

        //分页的插件
        PageInfo<AdminPojo> pageInfo = new PageInfo<AdminPojo> (list);

        //返回到前台
        request.setAttribute("pageInfo",pageInfo);

        //把搜索条件回填到页面
        request.setAttribute("ae",ae);

        return "adminlist";
    }

    /**
     * 根据用户id删除用户
     * @param aid 用户id
     * @return
     */
    @RequestMapping("/delAdmin")
    @ResponseBody
    public ResponseResult delAdmin(Integer aid){
        ResponseResult rr = new ResponseResult();

        //删除用户信息
        boolean bl = adminService.delAdmin(aid); //将状态修改

        if(bl){
            rr.setResult(FruitsFinal.SUCCESS_RESULT);
        }else{
            rr.setResult(FruitsFinal.FILED_RESULT);
            rr.setResultMsg("删除失败");
        }

        return rr;
    }

    //根据用户ids删除用户
    @RequestMapping("/delAdminByIds")
    @ResponseBody
    public ResponseResult delAdminByIds(String ids){
        ResponseResult rr = new ResponseResult();

        //删除多个用户
        boolean bl = adminService.delAdminByIds(ids);

        //删除成功
        if(bl){
            rr.setResult(FruitsFinal.SUCCESS_RESULT);
        }else{
            rr.setResult(FruitsFinal.FILED_RESULT);
            rr.setResultMsg("删除失败");
        }

        return rr;
    }

    @RequestMapping("/jumpAdd")
    public String jumpAdd(HttpServletRequest request){

        //查询所有的角色信息
        List<RolePojo> roles = roleService.queryRoles(null);

        request.setAttribute("roles",roles);

        return "adminadd";
    }

    @RequestMapping("adminAdd")
    public String addAdmin(AdminEntity ae){

        ae.setApass(StringUtil.MD5Encode(ae.getApass()));

        //添加用户到数据库
        boolean result = adminService.addAdmin(ae);

        return "addsuccess";
    }

    //跳转到编辑页面
    @RequestMapping("jumpEdit")
    public String jumpEdit(int aid,HttpServletRequest request){

        //查询所有的角色信息
        List<RolePojo> roles = roleService.queryRoles(null);
        request.setAttribute("roles",roles);

        //查询用户信息(用户的角色信息一起查询)
        AdminEntity ae = new AdminEntity();
        ae.setAid(aid);
        AdminPojo adminPojo = adminService.adminLogin(ae);
        request.setAttribute("adminPojo",adminPojo);

        return "adminedit";
    }

    //修改用户信息
    @RequestMapping("editAdmin")
    public String editAdmin(AdminEntity ae){

        //对用户信息进行修改
        try {
            boolean result = adminService.editAdmin(ae);
        } catch (Exception e) {
           //打印日志;
            System.out.println(e.getMessage());
            return "error";
        }

        return "addSuccess";
    }

    @RequestMapping("qiyong")
    @ResponseBody
    public ResponseResult qiyongAdmin(AdminEntity ae){

        ae.setAstatus(1); //设置用户的状态为启用

        boolean result = adminService.qiyong(ae); //启用该用户

        ResponseResult  rr = new ResponseResult();
        if(result){
           rr.setResult(FruitsFinal.SUCCESS_RESULT);
        }else{
            rr.setResult(FruitsFinal.FILED_RESULT);
            rr.setResultMsg("系统异常,请稍后再试");
        }

        return rr;
    }

    @RequestMapping("adminloginout")
    public String adminloginout(HttpSession session){

        session.removeAttribute("adminPojo");
        return "redirect:jump";
    }

}
